package com.chenchao.collection.properties;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/5 16:21
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.collection.properties.Test04.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 综合案例
 */
public class Test04 {
    static Properties properties = new Properties();
    public static final String URL = "myjava01/src/com/chenchao/collection/properties/conf.txt";
    static Scanner scanner = new Scanner(System.in);
    static Random random = new Random();

    public static void main(String[] args) {
        setCount(1);
        start();
        scanner.close();
    }

    /**
     * 开始游戏
     */
    private static void start() {
        while (true) {
            if (getCount() <= 0) {
                System.out.println("游戏次数已用尽，请前往充值");
                int i = Integer.parseInt(printInfo("充值请按1", "退出按0"));
                if (i == 0) {
                    return;
                } else {
                    addCount(Integer.parseInt(printInfo("请输入充值金额")));
                }
            } else {
                System.out.println("欢迎来到王者荣耀！");
                playGame();
                consumeCount();
            }
        }

    }

    /**
     * 添加指定次数
     * @param count 指定次数
     */
    private static void addCount(int count) {
        setCount(count+getCount());
        System.out.println("充值成功");
    }
    /**消耗1次数*/
    private static void consumeCount() {
        setCount(getCount()-1);
    }
    /**
     * 设置剩余次数
     * @param value 要设置的值
     */
    public static void setCount(int value) {
        try (FileWriter fileWriter = new FileWriter(URL)){
            properties.setProperty("Count", String.valueOf(value));
            properties.store(fileWriter,null);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**获取剩余次数*/
    private static int getCount() {
        try (FileReader fileReader = new FileReader(URL)) {
            properties.load(fileReader);
            return Integer.parseInt(properties.getProperty("Count"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 猜一下[0,100)的随机数
     */
    public static void playGame() {
        int value = random.nextInt(100);
        int answer;
        do {
            answer = Integer.parseInt(printInfo("请输入你的答案").trim());
            if (answer != value) {
                System.out.println(answer > value ? "你猜大了" : "你猜小了");
            }
        } while (value != answer);
        System.out.println("恭喜你猜对了");
    }

    /**
     * 打印提示信息并获取输入信息
     * @param str 提示信息
     * @return 返回值
     */
    public static String printInfo(String... str) {
        System.out.println(Arrays.toString(str));
        return scanner.nextLine();
    }

}
